<template>
  <div class="share-edit-container">
    <Header title="编辑分享" show-back />

    <div class="share-edit-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <van-loading type="spinner" size="24" />
        <p>正在加载分享信息...</p>
      </div>

      <!-- 编辑表单 -->
      <div v-else-if="shareInfo">
        <!-- 文件信息 -->
        <div class="file-card">
          <div class="file-icon">
            <van-icon
              name="share-o"
              color="#1989fa"
              size="24"
            />
          </div>
          <div class="file-info">
            <div class="file-name">{{ shareInfo.fileName }}</div>
            <div class="file-meta">
              <span>分享码：{{ shareInfo.shareCode }}</span>
            </div>
          </div>
        </div>

        <!-- 编辑表单 -->
        <van-form @submit="handleUpdateShare">
          <van-cell-group title="分享设置" inset>
            <van-field
              v-model="editForm.shareName"
              name="shareName"
              label="分享名称"
              placeholder="请输入分享名称"
              :rules="[{ required: true, message: '请输入分享名称' }]"
            />

            <van-field label="访问权限">
              <template #input>
                <van-radio-group v-model="editForm.permissions" direction="horizontal">
                  <van-radio :name="1">仅预览</van-radio>
                  <van-radio :name="2">可下载</van-radio>
                </van-radio-group>
              </template>
            </van-field>

            <van-field label="提取码">
              <template #input>
                <div class="password-setting">
                  <van-switch v-model="editForm.needPassword" />
                  <van-field
                    v-if="editForm.needPassword"
                    v-model="editForm.password"
                    placeholder="4位提取码"
                    maxlength="4"
                    style="flex: 1; margin-left: 12px;"
                    :rules="passwordRules"
                  >
                    <template #button>
                      <van-button size="small" @click="generatePassword">
                        随机生成
                      </van-button>
                    </template>
                  </van-field>
                </div>
              </template>
            </van-field>

            <van-field label="有效期">
              <template #input>
                <van-radio-group v-model="editForm.expireDays" direction="horizontal">
                  <van-radio :name="1">1天</van-radio>
                  <van-radio :name="7">7天</van-radio>
                  <van-radio :name="30">30天</van-radio>
                  <van-radio :name="-1">永久</van-radio>
                </van-radio-group>
              </template>
            </van-field>
          </van-cell-group>

          <div class="form-actions">
            <van-button
              round
              block
              type="primary"
              native-type="submit"
              :loading="updating"
            >
              保存修改
            </van-button>
          </div>
        </van-form>

        <!-- 分享统计 -->
        <van-cell-group title="分享统计" inset>
          <van-cell title="访问次数" :value="shareInfo.visitCount || 0" />
          <van-cell title="下载次数" :value="shareInfo.downloadCount || 0" />
          <van-cell title="创建时间" :value="formatDateTime(shareInfo.createTime)" />
        </van-cell-group>

        <!-- 危险操作 -->
        <div class="danger-zone">
          <van-button
            block
            type="danger"
            @click="handleCancelShare"
          >
            取消分享
          </van-button>
        </div>
      </div>

      <!-- 错误状态 -->
      <div v-else class="error-state">
        <van-empty
          image="error"
          description="分享不存在"
        >
          <van-button type="primary" @click="goBack">
            返回
          </van-button>
        </van-empty>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showLoadingToast, closeToast, showConfirmDialog } from 'vant'
import Header from '@/components/Header.vue'
import { useShareStore } from '@/stores/share'
import { updateShare, type CreateShareParams } from '@/api/share'
import type { ShareInfo } from '@/api/share'

const router = useRouter()
const route = useRoute()
const shareStore = useShareStore()

// 状态
const loading = ref(true)
const updating = ref(false)
const shareInfo = ref<ShareInfo | null>(null)

// 编辑表单
const editForm = ref({
  shareName: '',
  permissions: 2,
  needPassword: false,
  password: '',
  expireDays: 7
})

// 密码验证规则
const passwordRules = computed(() => [
  {
    validator: (value: string) => {
      if (editForm.value.needPassword && (!value || value.length !== 4)) {
        return '请输入4位提取码'
      }
      return true
    }
  }
])

// 方法
const formatDateTime = (dateStr: string): string => {
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const generatePassword = () => {
  const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  let password = ''
  for (let i = 0; i < 4; i++) {
    password += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  editForm.value.password = password
}

const goBack = () => {
  router.back()
}

const loadShareInfo = async () => {
  const shareId = parseInt(route.params.shareId as string)

  if (!shareId) {
    showToast('分享ID参数错误')
    router.back()
    return
  }

  try {
    loading.value = true

    // 从分享列表中查找对应的分享信息
    const { shareList } = shareStore
    const share = shareList.find(s => s.id === shareId)

    if (share) {
      shareInfo.value = share

      // 初始化编辑表单
      editForm.value = {
        shareName: share.shareName,
        permissions: share.permissions,
        needPassword: !!share.password,
        password: share.password || '',
        expireDays: getExpireDaysFromTime(share.expireTime)
      }
    } else {
      // 如果列表中没有，尝试重新获取分享列表
      await shareStore.fetchMyShareList()
      const refreshedShare = shareStore.shareList.find(s => s.id === shareId)

      if (refreshedShare) {
        shareInfo.value = refreshedShare
        editForm.value = {
          shareName: refreshedShare.shareName,
          permissions: refreshedShare.permissions,
          needPassword: !!refreshedShare.password,
          password: refreshedShare.password || '',
          expireDays: getExpireDaysFromTime(refreshedShare.expireTime)
        }
      } else {
        shareInfo.value = null
      }
    }
  } catch (error) {
    console.error('获取分享信息失败:', error)
    shareInfo.value = null
  } finally {
    loading.value = false
  }
}

const getExpireDaysFromTime = (expireTime?: string): number => {
  if (!expireTime) return -1 // 永久有效

  const expire = new Date(expireTime)
  const now = new Date()
  const diffTime = expire.getTime() - now.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

  // 根据剩余天数判断最接近的选项
  if (diffDays <= 1) return 1
  if (diffDays <= 7) return 7
  if (diffDays <= 30) return 30
  return -1
}

const handleUpdateShare = async () => {
  if (!shareInfo.value) {
    showToast('分享信息不存在')
    return
  }

  if (editForm.value.needPassword && editForm.value.password.length !== 4) {
    showToast('请输入4位提取码')
    return
  }

  updating.value = true
  showLoadingToast({
    message: '正在更新分享设置...',
    duration: 0
  })

  try {
    // 计算过期时间
    let expireTimeStr = ''
    if (editForm.value.expireDays > 0) {
      const expireDate = new Date()
      expireDate.setDate(expireDate.getDate() + editForm.value.expireDays)
      expireTimeStr = expireDate.toISOString().slice(0, 19).replace('T', ' ')
    }

    const params: Partial<CreateShareParams> = {
      shareName: editForm.value.shareName,
      permissions: editForm.value.permissions,
      password: editForm.value.needPassword ? editForm.value.password : undefined,
      expireTimeStr: expireTimeStr || undefined
    }

    await updateShare(shareInfo.value.id, params)

    closeToast()
    showToast({
      type: 'success',
      message: '分享设置已更新'
    })

    // 刷新分享列表
    await shareStore.fetchMyShareList()

    // 返回分享列表
    router.back()
  } catch (error: any) {
    closeToast()
    showToast({
      type: 'fail',
      message: error.message || '更新分享设置失败'
    })
  } finally {
    updating.value = false
  }
}

const handleCancelShare = async () => {
  if (!shareInfo.value) return

  const confirmed = await showConfirmDialog({
    title: '确认取消分享',
    message: `确定要取消分享 "${shareInfo.value.shareName}" 吗？取消后分享链接将失效。`
  })

  if (confirmed) {
    try {
      await shareStore.removeShare(shareInfo.value.id)
      router.back()
    } catch (error: any) {
      showToast({
        type: 'fail',
        message: error.message || '取消分享失败'
      })
    }
  }
}

onMounted(() => {
  loadShareInfo()
})
</script>

<style scoped>
.share-edit-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
}

.share-edit-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #969799;
}

.loading-state p {
  margin-top: 12px;
  font-size: 14px;
}

.error-state {
  padding: 40px 20px;
}

.file-card {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.file-icon {
  margin-right: 12px;
  flex-shrink: 0;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 16px;
  color: #323233;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-meta {
  font-size: 12px;
  color: #969799;
}

.password-setting {
  display: flex;
  align-items: center;
  width: 100%;
}

.form-actions {
  margin-top: 24px;
  padding: 0 16px;
}

.danger-zone {
  margin-top: 24px;
  padding: 16px;
}

:deep(.van-cell-group--inset) {
  margin: 16px 0;
}

:deep(.van-radio-group) {
  display: flex;
  gap: 16px;
}

:deep(.van-field__control) {
  text-align: right;
}
</style>